package cn.javasea.patterns.googleEventBus;

import cn.javasea.patterns.googleEventBus.obv.RegNotificationObserver;
import cn.javasea.patterns.googleEventBus.obv.RegPromotionObserver;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Executors;

@RestController
public class UserController {
    @Autowired
    private ObvUserService userService; // 依赖注入

    private EventBus eventBus;

    private static final int DEFAULT_EVENTBUS_THREAD_POOL_SIZE = 20;

    /**
     * 通过spring的构造器注入了bean
     * @param regNotificationObserver
     * @param regPromotionObserver
     */
    public UserController(RegNotificationObserver regNotificationObserver, RegPromotionObserver regPromotionObserver) {
//        eventBus = new EventBus(); // 同步阻塞模式
        eventBus = new AsyncEventBus(Executors.newFixedThreadPool(DEFAULT_EVENTBUS_THREAD_POOL_SIZE));

        eventBus.register(regNotificationObserver);
        eventBus.register(regPromotionObserver);

//        for (Object observer : regObserverList) {
//            eventBus.register(observer);
//        }
    }


    /** http://localhost:8080/obv-reg */
    @GetMapping("/obv-reg")
    public Long register(String telephone, String password) {
        //省略输入参数的校验代码
//省略userService.register()异常的try-catch代码
        Long userId = userService.register(telephone, password);
        eventBus.post(userId);
        return userId;
    }
}
